package com.linkage.event.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.linkage.common.base.RequestInfo;
import com.linkage.common.base.ResponseInfo;
import com.linkage.event.pojo.entity.*;
import com.linkage.event.pojo.vo.EventMessageVo;
import com.linkage.event.pojo.vo.EventShowVo;
import com.linkage.event.pojo.vo.EventTypeVo;
import com.linkage.event.service.EventOperationService;
import com.linkage.event.service.EventTypeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

/**
 * 事件处理controller
 */
@Slf4j
@RestController
@RequestMapping(value = "/event")
public class EventController {

    @Autowired
    private EventOperationService eventOperationService;
    @Autowired
    private EventTypeService eventTypeService;

    /**
     * 创建事件
     * @param em
     * @return
     */
    @RequestMapping(value = "/createEvent", method = RequestMethod.POST)
    public String createEvent( @RequestBody RequestInfo<EventMessage> em){
        try {
            String eventMsgId = this.eventOperationService.createEvent(em.getBuss());
            return ResponseInfo.success(MapUtil.builder().put("eventMsgId",eventMsgId).build()).toString();
        } catch (Exception e) {
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }

    /**
     * 提交事件
     * @param et
     * @return
     */
    @RequestMapping(value = "/commitEvent", method = RequestMethod.POST)
    public String commitEvent(@RequestBody RequestInfo<EventTask> et){
        try{
            if(StrUtil.isEmpty(et.getBuss().getEventMsgId())){
                return ResponseInfo.error("事件ID为空！").toString();
            }
            this.eventOperationService.commitEvent(et.getBuss(),et.getBase().getUsertoken());
            return JSONUtil.toJsonStr(ResponseInfo.success());
        }catch(Exception e){
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }

    /**
     * 指派事件
     * @param requestInfo
     * @return
     */
    @RequestMapping(value = "/designateEvent", method = RequestMethod.POST)
    public String designateEvent(@RequestBody RequestInfo<Map<String,Object>> requestInfo){
        try{
            String token = requestInfo.getBase().getUsertoken();
            if(StrUtil.isEmpty(token)){
                return ResponseInfo.error("usertoken参数为空").toString();
            }
        	String eventMsgId = (String)requestInfo.getBuss().get("eventMsgId");
        	 List<String> designateUserIds = (List)requestInfo.getBuss().get("designateUserIds");
            this.eventOperationService.designateEvent(eventMsgId, designateUserIds,token);
            return JSONUtil.toJsonStr(ResponseInfo.success());
        }catch(Exception e){
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }


    /**
     * 依据事件id和完成人修改任务信息
     * @param et
     * @return
     */
    @RequestMapping(value = "/updateEventTask", method = RequestMethod.POST)
    public String updateEventTask(@RequestBody RequestInfo<EventTask> et){
        try{
            this.eventOperationService.updateEventTaskByPrimaryKeySelective(et.getBuss());
            return JSONUtil.toJsonStr(ResponseInfo.success());
        }catch(Exception e){
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }

    /**
     * 事件详情
     * @param eventMessage
     * @return
     */
    @RequestMapping(value = "/singleEventShow", method = RequestMethod.POST)
    public String singleEventShow(@RequestBody RequestInfo<EventMessage> eventMessage){
        try {
            EventShowVo eventShowVo = this.eventOperationService.singleEventShow(eventMessage.getBuss().getId());
            return JSONUtil.toJsonStr(ResponseInfo.success(eventShowVo));
        } catch (Exception e) {
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }

    /**
     * 事件列表（带模糊查询）
     * @param requestInfo
     * @return
     */
    @RequestMapping(value = "/listEventShow", method = RequestMethod.POST)
    public String listEventShow(@RequestBody RequestInfo<Map> requestInfo){
        String userToken = requestInfo.getBase().getUsertoken();
        if(StrUtil.isEmpty(userToken)){
            return ResponseInfo.error("userToken参数为空").toString();
        }
        try {
            Integer pageNo = null;
            Integer pageSize = null;
            if(requestInfo.getBase().getPageNum() != null){
                pageNo = Integer.parseInt(requestInfo.getBase().getPageNum());
            }
            if(requestInfo.getBase().getPageRows() != null){
                pageSize = Integer.parseInt(requestInfo.getBase().getPageRows());
            }
            String title = requestInfo.getBuss().containsKey("title")?String.valueOf(requestInfo.getBuss().get("title")):null;
            String type = requestInfo.getBuss().containsKey("type")?String.valueOf(requestInfo.getBuss().get("type")):null;
            String status = requestInfo.getBuss().containsKey("status")?String.valueOf(requestInfo.getBuss().get("status")):null;
            String isRecommend=requestInfo.getBuss().containsKey("isRecommend")?String.valueOf(requestInfo.getBuss().get("isRecommend")):null;
            String flag = requestInfo.getBuss().containsKey("flag")? String.valueOf(requestInfo.getBuss().get("flag")):"0";
            String startDate = requestInfo.getBuss().containsKey("startDate")?String.valueOf(requestInfo.getBuss().get("startDate")):null;
            String endDate = requestInfo.getBuss().containsKey("endDate")?String.valueOf(requestInfo.getBuss().get("endDate")):null;
            EventMessage message = EventMessage.builder().eventDisposeStatus(status).eventType(type).eventTitle(title).recommendStatus(isRecommend).trainingType(flag).build();
            PageInfo<EventMessageVo> pageInfo =  this.eventOperationService.listEventShow(pageNo, pageSize, message, startDate, endDate, userToken);
            return JSONUtil.toJsonStr(ResponseInfo.successWithPage(pageInfo));
        } catch (Exception e) {
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }


    /**
     * 依据事件一级类型查询二级类型
     * @param type
     * @return
     */
    @RequestMapping(value = "/listEventTypeBySuperiorTypeCode", method = RequestMethod.POST)
    public String listEventTypeBySuperiorTypeCode(@RequestBody RequestInfo<EventType> type){
        try {
            List<EventType> eventTypes = this.eventOperationService.selectBySuperiorTypeCode(type.getBuss().getSuperiorTypeCode(),type.getBuss().getEnableStatus());
            return JSONUtil.toJsonStr(ResponseInfo.success(eventTypes));
        } catch (Exception e) {
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }

    /**
     * 依据事件类型代码查询事件类型信息
     * @param type
     * @return
     */
    @RequestMapping(value = "/singleEventTypeByEventTypeCode", method = RequestMethod.POST)
    public String singleEventTypeByEventTypeCode(@RequestBody RequestInfo<EventType> type){
        try {
            EventType eventType = this.eventOperationService.selectByEventTypePrimaryKey(type.getBuss().getEventTypeCode());
            return JSONUtil.toJsonStr(ResponseInfo.success(eventType));
        } catch (Exception e) {
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }

    /**
     * 通过事件ID查询任务信息
     * @param eventMessage
     * @return
     */
    @RequestMapping(value = "/selectEventTaskByEventMsgId", method = RequestMethod.POST)
    public String selectEventTaskByEventMsgId(@RequestBody RequestInfo<EventMessage> eventMessage){
        try {
            List<EventTask> eventTasks = this.eventOperationService.selectEventTaskByEventMsgId(eventMessage.getBuss().getId());
            return JSONUtil.toJsonStr(ResponseInfo.success(eventTasks));
        } catch (Exception e) {
            log.error("",e);
            return JSONUtil.toJsonStr(ResponseInfo.error(e.getMessage()));
        }
    }


    /**
     * 查询所有可用的一级目录及二级目录
     * @return
     */
    @PostMapping(value="/getEventTypeList")
    public String getEventTypeList(@RequestBody RequestInfo<EventType> type){
        List<EventTypeVo> list = eventTypeService.getEventTypeList(type.getBuss().getType(),type.getBuss().getEnableStatus());
        return ResponseInfo.success(list).toString();
    }

    /**
     * 新增事件类型
     * @param eventType
     * @return
     */
    @PostMapping(value = "/addEventType")
    public String addEventType(@RequestBody RequestInfo<EventType> eventType){
        eventTypeService.insert(eventType.getBuss());
        return ResponseInfo.success().toString();
    }

    /**
     * 修改事件类型
     * @param eventType
     * @return
     */
    @PostMapping(value = "/updateEventType")
    public String updateEventType(@RequestBody RequestInfo<EventType> eventType){
        eventTypeService.update(eventType.getBuss());
        return ResponseInfo.success().toString();
    }

    /**
     * 删除事件类型
     * @param eventTypeRequestInfo
     * @return
     */
    @PostMapping(value = "/delEventType")
    public String delEventType(@RequestBody RequestInfo<EventType> eventTypeRequestInfo){
        eventTypeService.delete(eventTypeRequestInfo.getBuss().getEventTypeCode());
        return ResponseInfo.success().toString();
    }

    /**
     * 查询后台统计接口
     * @return
     */
    @PostMapping(value="/statisticEventCount")
    public String statisticEventCount(@RequestBody RequestInfo<Map> user){
        String role = user.getBase().getUsertoken().split(":")[2];
        String userCode = user.getBuss().get("userCode").toString();
        if("CJGLY-3".equals(role)){
            userCode = null;
        }
        Map<String, Integer> map = eventOperationService.statisticEventCount(userCode,user.getBase().getUsertoken());
        log.info("查询事件类型统计为："+map.toString());
        return ResponseInfo.success(map).toString();
    }

    /**
     * 按角色信息查询事件数
     * @param map roleId: 0-群众，1-下级，2-内部 userCode
     * @return
     */
    @PostMapping(value = "/statisticEventByRole")
    public String statisticEventByRole(@RequestBody RequestInfo<Map<String,String>> map){
        String role = map.getBase().getUsertoken().split(":")[2];
        String userCode = map.getBuss().get("userCode");
        if("CJGLY-3".equals(role)){
            userCode = null;
        }
        List<Map<String, Object>> result = eventOperationService.statisticEventCountByPersonClass(role,userCode,map.getBase().getUsertoken());
        return ResponseInfo.success(result).toString();
    }

    /**
     * app端事件分页查询
     * @return
     */
    @PostMapping(value = "/queryList4App")
    public String queryListForApp(@RequestBody RequestInfo<Map> requestInfo){
        log.info(requestInfo.toString());
        Integer pageNo = Integer.parseInt(requestInfo.getBase().getPageNum());
        Integer pageSize = Integer.parseInt(requestInfo.getBase().getPageRows());
        String userCode = requestInfo.getBuss().containsKey("userCode")? String.valueOf(requestInfo.getBuss().get("userCode")):null;
        String solveStatus = requestInfo.getBuss().containsKey("solveStatus")? String.valueOf(requestInfo.getBuss().get("solveStatus")):null;
        String eventDisposeStatus = requestInfo.getBuss().containsKey("eventDisposeStatus")? String.valueOf(requestInfo.getBuss().get("eventDisposeStatus")):null;
        EventTask eventTask = new EventTask();
        eventTask.setUserId(userCode);
        eventTask.setSolveStatus(solveStatus);
        PageInfo<EventMessage> pageInfo = eventOperationService.queryListByPage(pageNo, pageSize, eventTask, eventDisposeStatus);
        return ResponseInfo.successWithPage(pageInfo).toString();
    }

}
